package service.Impl;

import exception.BusinessException;
import model.Item;
import model.Order;
import service.IOrderRepository;
import service.IOrderService;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.List;
/**
 * 订单服务基础实现
 */
public abstract class OrderServiceImpl implements IOrderService {
    protected final IOrderRepository repository;
    protected final Clock systemClock; // 可用于真实环境时间获取

    protected OrderServiceImpl(IOrderRepository repository) {
        this.repository = repository;
        this.systemClock = Clock.systemDefaultZone();
    }
    // 真实环境使用的创建方法（自动获取当前时间）
    @Override
    public Order createOrder(List<Item> items, boolean isVIP) {
        return createOrder(items, isVIP, LocalDateTime.now(systemClock));
    }
    @Override
    public void cancelOrder(String orderId, LocalDateTime currentTime){
        Order order = repository.findById(orderId);
        if (order == null){
            throw new BusinessException("订单不存在: " + orderId);
        }
        //规则一
        if (order.getStatus() == Order.OrderStatus.PAID){
            throw new BusinessException("已支付的订单不可取消");
        }
        //规则二
        if (currentTime.minusMinutes(30).isAfter(currentTime)){
            repository.updateStatus(orderId, Order.OrderStatus.CANCELLED);
        }else {
            throw new BusinessException("订单创建时间未超过30分钟，不能手动取消");
        }

    }

    // 测试专用方法（需子类实现具体逻辑）
    @Override
    public abstract Order createOrder(List<Item> items, boolean isVIP, LocalDateTime currentTime);
}

